package com.lagou.oss;


import com.aliyun.oss.model.OSSObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

/**
 * Created with IntelliJ IDEA by ChouFy on 2020-08-04.
 *
 * @author chouFy
 */

@RestController
@RequestMapping("/pic")
public class UploadController {
    @Autowired
    private FileUpLoadService fileUpLoadService;

    @PostMapping("/upload")
    public UpLoadResult upload(@RequestParam("file") MultipartFile multipartFile) {
        return fileUpLoadService.upload(multipartFile);
    }



    @RequestMapping("/del")
    public UpLoadResult delete(@RequestParam("name") String name){
        return fileUpLoadService.delete(name);
    }



    @RequestMapping("/download")
    public void download(@RequestParam("name") String name, HttpServletResponse response){

        OSSObject ossObject = fileUpLoadService.download(name);
        if (ossObject != null) {
            InputStream inputStream = ossObject.getObjectContent();
            int buffer = 1024 * 10;
            byte data[] = new byte[buffer];
            try {
                response.setContentType("application/octet-stream");
                // 文件名可以任意指定

                String newName = name.substring(name.lastIndexOf("/"));
                //将文件名转为ASCLL编码
                response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(newName,"UTF-8"));
                int read;
                while ((read = inputStream.read(data)) != -1) {
                    response.getOutputStream().write(data, 0, read);
                }
                response.getOutputStream().flush();
                response.getOutputStream().close();
                ossObject.close();
            } catch (UnsupportedEncodingException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }

    }

    @RequestMapping("/test")
    public Object test(){
        return "hello word";
    }
}

